package socket;



import dao.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class HelloServer {
     private static final Logger logger = LoggerFactory.getLogger(HelloServer.class);

     public void start (int port){
         // 1、创建socket对象
         try {
             ServerSocket serverSocket = new ServerSocket(port);
             Socket socket;
             // 2、通过accept()方法监听客户端请求
             while((socket = serverSocket.accept()) != null){
                 logger.info("client connect");
                 try {
                     ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                     // 3、接收客户端内容
                     Message content = (Message) objectInputStream.readObject();
                     logger.info("server receive message: " + content.getMessage());
                     content.setMessage("new Content");
                     // 4、发送内容给客户端
                     ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                     objectOutputStream.writeObject(content);
                     objectOutputStream.flush();
                 } catch (ClassNotFoundException e) {
                     logger.error("occur ClassNotFoundException", e);
                 }
             }
         } catch (IOException e) {
             logger.error("occur IOException", e);
         }
     }

    public static void main(String[] args) {
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        ExecutorService threadPool = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(100), threadFactory);
        threadPool.execute(() -> {
            HelloServer helloServer = new HelloServer();
            helloServer.start(6666);
        });

//            ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
//            for (int i = 0; i < 2; i++) {
//                final int index = i;
//                cachedThreadPool.execute(() -> {
//                    System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
//                });
//            }

     }
}
